package com.xwqiang.config;

import com.alibaba.fastjson.JSON;
import com.xwqiang.filter.JwtAuthTokenFilter;
import com.xwqiang.utils.ErrCode;
import com.xwqiang.utils.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private JwtAuthTokenFilter jwtAuthTokenFilter;

    /**
     * 配置密码加密算法
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }


    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http); 去除spring默认的登录认证，使用自定义的
        //禁用csrf
        http.csrf().disable();
        //请求url权限控制
        http.authorizeRequests()
                .antMatchers("/admin/login").permitAll()
                .anyRequest().authenticated();
        //用户登录控制

//        http.formLogin()
//                .successHandler((request, response, authentication) -> {
//                    System.out.println("登录成功");
//                    Resp<Object> data = Resp.success("登录成功");
//                    response.setContentType("application/json;charset=utf-8");
//                    response.getWriter().write(JSON.toJSONString(data));
//                })
//                .failureHandler((request, response, exception) -> {
//                    System.out.println("登录失败");
//                    Resp<Object> data = Resp.error(AppExceptionCodeMsg.USER_NAME_PWD_ERROR);
//                    response.setContentType("application/json;charset=utf-8");
//                    response.getWriter().write(JSON.toJSONString(data));
//                });

        //异常控制
        http.exceptionHandling()
                .accessDeniedHandler((request,response,exception)->{
                    System.out.println(exception.getMessage());
                    Resp<Object> data = Resp.error(ErrCode.USER_NAME_PWD_ERROR);
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(JSON.toJSONString(data));
                }).authenticationEntryPoint((request,response,exception)->{
                    System.out.println(exception.getMessage());
                    Resp<Object> data = Resp.error(ErrCode.USER_NAME_PWD_ERROR);
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(JSON.toJSONString(data));
                });


        //回话管理
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        //将自己jwt过滤器加在默认的认证拦截器之前
        http.addFilterBefore(jwtAuthTokenFilter, UsernamePasswordAuthenticationFilter.class);

    }


}
